from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
print("*"*10+"图书自动检索脚本启动"+"*"*10)
print("选择账号-1.原有账号，2.更改/新建账号")
def inputf(xpath,word):#使用javascript强制输入
    x=driver.find_element(By.XPATH, xpath)
    driver.execute_script("arguments[0].value = arguments[1]",x,"%s"%word)
while True:#选择账户
    choose = eval(input("Enter:"))
    if choose==1:
        import test0
        print("已导入")
        break
    elif choose==2:
        f=open("test0.py","w")
        account = eval(input("Enter your account:"))
        password = input("Enter your password:")
        f.write("account=%d\n"%account)
        f.write("password='%s'\n"%password)
        print("已修改")
        f.close()
        import test0
        break
    else:
        print("输错了")
book = input("Enterbookname:")
#开始模拟浏览器


#1.模拟登录
driver = webdriver.Edge()
driver.get("https://wrdvpn.dlnu.edu.cn/http/77726476706e69737468656265737421f1e2559434357a467b1ac7a8945b367b94f42598d6d7/authserver/login?service=https%3A%2F%2Fwrdvpn.dlnu.edu.cn%2Flogin%3Fcas_login%3Dtrue")
driver.find_element(By.ID, "username").send_keys(test0.account)
inputf("//*[@class='password item']/input",test0.password)
driver.find_element(By.ID, "login_submit").click()
time.sleep(1)#如果报错请延长时间

#2.进入新窗口
current_window = driver.current_window_handle
driver.find_element(By.XPATH,"//*[@class='block-group__content']/div[2]").click()

#3.切换driver至新窗口
handles = driver.window_handles
new_window = [handle for handle in handles if handle!=current_window][0]
driver.switch_to.window(new_window)

#4.进入检索页面
x=driver.find_element(By.XPATH,"//*[@class='bottom-list clearfix']/li[1]/a")
driver.execute_script("arguments[0].click();", x)#疑似进入按钮被隐藏，使用javascript强行进入
time.sleep(1)#如果报错请延长时间

#5.搜索书籍名称
elements = driver.find_elements(By.XPATH,"//*[@valuekey='value']")
element = elements[1]
element.send_keys("%s"%book)
x=driver.find_element(By.XPATH,"//*[@class='iconfont iconfangdajing']")
driver.execute_script("arguments[0].click();", x)

#6.完成查找，输出书籍列
print("以下是查找到的书籍：")
booktitles=WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.XPATH,"//*[@class='book-info-con']/div/span")))
i=1
for booktitle in booktitles:
    text=booktitle.text
    text.strip("\n")
    print("%s"%i+":"+text)
    i+=1

#7.获得图书号,打印图书索书号等
bookint=eval(input("请输入你要借那一本书（数字）："))
books=driver.find_elements(By.XPATH,"//*[@class='book-num']")
book=books[bookint-1]
book.click()
print("已为你找到%s：\n"%booktitles[bookint-1].text)
results=driver.find_elements(By.XPATH,"//*[@class='el-table__row']")
for result in results:
    content = result.find_elements(By.XPATH,"td")
    x=1
    for i in content:
        if x!=2:
            print(i.text)
        x+=1
    print("\n")